package com.searchcloud.web;

import com.searchcloud.service.WeiXinService;
import com.searchcloud.utils.ConstantUtils;
import com.searchcloud.utils.SHA1;
import com.searchcloud.utils.SpellComparator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author:ike
 * @function:
 * @creatTime:17:34 2017/10/25
 **/
@Controller
@RequestMapping("/weiXinTokenController")
public class WeiXinTokenController {
    @Autowired
    public WeiXinService weiXinService;
    public boolean isGet;

    @RequestMapping(value = "/processTokenMsg.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void processTokenMsg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        if (request.getMethod().toLowerCase().equals("get")) {
            isGet = true;
        }
        if (isGet) {
            //加密签名
            String signature = request.getParameter("signature");
            //时间戳
            String timestamp = request.getParameter("timestamp");
            //随机数
            String nonce = request.getParameter("nonce");
            //随机字符串
            String echoStr = request.getParameter("echostr");
            //排序加密
            List<String> paramList = new ArrayList<String>();
            paramList.add(ConstantUtils.TOKEN);
            paramList.add(timestamp);
            paramList.add(nonce);
            Collections.sort(paramList, new SpellComparator());
            //拼接排序后的数据
            String wxStr = paramList.get(0) + paramList.get(1) + paramList.get(2);
            //进行sha1加密对比
            if (SHA1.encode(wxStr).equals(signature.trim())) {
                //如果比对成功往微信写echostr
                response.getWriter().write(echoStr);
                System.out.println("<!----------微信接入服务器成功" + echoStr + "----------!>");
            } else {
                System.out.println("<!----------微信接入服务器失败" + echoStr + "----------!>");
            }

        } else {
            String msg = weiXinService.processWeiXinMsg(request);
            response.getWriter().write(msg);
        }

    }
    /**
     * 创建菜单
     */
    @RequestMapping(value = "/createMenu.do")
    public void createMenu() {
        weiXinService.createWeiXinMenu();
    }
}
